<?php

namespace app\admin\controller;

use app\admin\service\UserService;
use app\BaseController;
use app\model\CrisisBehaviorModel;
use app\model\CrisisTypeModel;
use app\model\FollowUserModel;
use app\model\InterfereBehaviorModel;
use app\model\InterfereUserModel;
use app\model\not_del\UserModel as NotDelUserModel;
use think\App;

class InterfereStatistics extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 危机人数统计
     * @return bool|string
     */
    public function NumberPeople(): bool|string
    {
        try {
            $InterfereUserModel = new InterfereUserModel();
            $unitId = $this->userData['unit_id'];
            $monthStart = strtotime(date("Y-m-01 00:00:00")); // 精确到当月第一天0点

            // 当月危机人数：数据库层面去重计数，减少内存占用
            $total = $InterfereUserModel->where([
                ['unit_id', '=', $unitId],
                ['time', '>=', $monthStart] // 改为>=更精确匹配当月数据
            ])->distinct('uid')->count('uid');

            // 历史危机人数：同样使用数据库去重计数
            $history = $InterfereUserModel->where([
                ['unit_id', '=', $unitId]
            ])->distinct('uid')->count('uid');

            return success([
                'total' => $total,
                'history' => $history
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 危机男女比率
     * @return bool|string
     */
    public function MenWomen(): bool|string
    {
        try {
            $InterfereUserModel = new InterfereUserModel();
            $uid = $InterfereUserModel->where([
                ['unit_id','=',$this->userData['unit_id']]
            ])->distinct(true)->column('uid');
            if (!empty($uid)){
                $data['total'] = count($uid);
                $UserModel = new NotDelUserModel();
                $data['boy'] = $UserModel->where([
                    ['id','in',$uid],
                    ['sex','=',1]
                ])->count();
                $data['girl'] = $data['total'] - $data['boy'];
            }else{
                $data['total'] = 0;
                $data['boy'] = 0;
                $data['girl'] = 0;
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 异常类型
     * @return bool|string
     */
    public function Exception(): bool|string
    {
        try {
            $InterfereUserModel = new InterfereUserModel();
            $InterfereBehaviorModel = new InterfereBehaviorModel();
            $CrisisBehaviorModel = new CrisisBehaviorModel();
            $Behavior = $CrisisBehaviorModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['status','=',1]
            ])->select()->toArray();
            $data = [];
            foreach ($Behavior as $value){
                $data['name'][] = $value['name'];
                $interfere_id = $InterfereBehaviorModel->where('behavior_id','=',$value['id'])->distinct(true)->column('interfere_id');
                $data['num'][] = $InterfereUserModel->where('id','in',$interfere_id)->distinct(true)->count('uid');
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 问题类型人数统计
     * @return bool|string
     */
    public function QuestionType(): bool|string
    {
        try {
            $CrisisTypeModel = new CrisisTypeModel();
            $InterfereUserModel = new InterfereUserModel();
            $type = $CrisisTypeModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['status','=',1]
            ])->select()->toArray();
            $data = [];
            $people_num = 0;
            foreach ($type as $value){
                $data['name'][] = $value['name'];
                $num = $InterfereUserModel->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['type_id','=',$value['id']]
                ])->distinct(true)->count('uid');
                $data['num'][] = $num;
                $people_num += $num;
            }
            $total = $InterfereUserModel->where('unit_id','=',$this->userData['unit_id'])->count('id');
            return success([
                'data' => $data,
                'people_num' => $people_num,
                'total' => $total
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 危机人员分布统计
     * @return bool|string
     */
    public function PersonnelDistribution(): bool|string
    {
        try {
            $UserModel = new NotDelUserModel();
            $InterfereUserModel = new InterfereUserModel();
            $uids = $InterfereUserModel->where('unit_id','=',$this->userData['unit_id'])->distinct(true)->column('uid');
            $user = $UserModel->where('id','in',$uids)->field('id,department_id,sex')->select()->toArray();
            $data = [];
            $UserService = new UserService($this->app);
            $NotDelDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
            foreach ($user as $value){
                $value['department_name'] = $NotDelDepartment[$value['department_id']]['all_name']??'';
                $data[$value['department_id']][] = $value;
            }
            $data2 = [];
            foreach ($data as $item){
                $value = [
                    'name' => '',
                    'total' => 0,
                    'boy' => 0,
                    'girl' => 0,
                ];
                foreach ($item as $items){
                    $value['name'] = $items['department_name'];
                    $value['total']++;
                    if ($items['sex'] == 1){
                        $value['boy']++;
                    }else{
                        $value['girl']++;
                    }
                }
                $data2[] = $value;
            }
            return success($data2);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 危机干预及重点关注人员统计
     * @return bool|string
     */
    public function staff(): bool|string
    {
        try {
            $UserModel = new NotDelUserModel();
            $InterfereUserModel = new InterfereUserModel();
            $FollowUserModel = new FollowUserModel();
            //干预
            $uids = $InterfereUserModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['status','=',0],
                ['move_status','=',1]
            ])->distinct(true)->column('uid');
            $InterfereBoy = $UserModel->where([
                ['id','in',$uids],
                ['sex','=',1]
            ])->count('id');
            $InterfereGirl = count($uids) - $InterfereBoy;
            //关注
            $uids = $FollowUserModel->where([
                ['unit_id','=',$this->userData['unit_id']]
            ])->distinct(true)->column('uid');
            $FollowBoy = $UserModel->where([
                ['id','in',$uids],
                ['sex','=',1]
            ])->count('id');
            $FollowGirl = count($uids) - $FollowBoy;
            $date = custom_time();
            $data = [];
            foreach ($date as $value){
                $data['date'][] = date('d',strtotime($value['value']));
                $data['interfere'][] = $InterfereUserModel->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['time','between',[strtotime($value['start_time']),strtotime($value['end_time'])]],
                    ['status','=',0],
                    ['move_status','=',1]
                ])->distinct(true)->count('uid');
                $data['follow'][] = $FollowUserModel->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['time','between',[strtotime($value['start_time']),strtotime($value['end_time'])]]
                ])->distinct(true)->count('uid');
            }
            return success([
                'data' => $data,
                'interfere_boy' => $InterfereBoy,
                'interfere_girl' => $InterfereGirl,
                'follow_boy' => $FollowBoy,
                'follow_girl' => $FollowGirl
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 本期新增数据-月报
     * @return bool|string
     */
    public function MonthAddData(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'date|时间' => 'require'
            ]);
            $start_time = strtotime($param['date'] . '-01');
            $end_time = strtotime(date('Y-m-t 23:59:59', $start_time));
            $InterfereUserModel = new InterfereUserModel();
            $FollowUserModel = new FollowUserModel();

            //新增待干预
            $NewInterfereNum = $InterfereUserModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['move_status','=',0],
                ['time','between',[$start_time, $end_time]]
            ])->distinct(true)->count('uid');
            //新增关注
            $NewFollowNum = $FollowUserModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['time','between',[$start_time, $end_time]],
            ])->distinct(true)->count('uid');
            //已结束干预
            $NewInterfereNum2 = $InterfereUserModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['status','=',1],
                ['time','between',[$start_time, $end_time]]
            ])->distinct(true)->count('uid');
            //待处理干预;
            $NewInterfereNum3 = $InterfereUserModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['status','=',0],
                ['move_status','=',1],
                ['time','between',[$start_time, $end_time]]
            ])->distinct(true)->count('uid');
            return success([
                'new_interfere_num' => $NewInterfereNum3,
                'new_interfere_num2' => $NewInterfereNum2,
                'new_interfere_num3' => $NewInterfereNum,
                'new_follow_num' => $NewFollowNum,
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 本月干预人员中男女比例-月报
     * @return bool|string
     */
    public function MonthSexRatio(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'date|时间' => 'require'
            ]);
            $start_time = strtotime($param['date'] . '-01');
            $end_time = strtotime(date('Y-m-t 23:59:59', $start_time));
            $InterfereUserModel = new InterfereUserModel();
            $UserModel = new NotDelUserModel();
            $uids = $InterfereUserModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['time','between',[$start_time, $end_time]]
            ])->distinct(true)->column('uid');
            $data['boy'] = $UserModel->where([
                ['id','in',$uids],
                ['sex','=',1]
            ])->count();
            $data['girl'] = $UserModel->where([
                ['id','in',$uids],
                ['sex','=',2]
            ])->count();
            $data['total'] = $data['boy'] + $data['girl'];
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 本期异常情况统计-月报
     * @return bool|string
     */
    public function MonthException(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'date|时间' => 'require'
            ]);
            $start_time = strtotime($param['date'] . '-01');
            $end_time = strtotime(date('Y-m-t 23:59:59', $start_time));
            $InterfereUserModel = new InterfereUserModel();
            $InterfereBehaviorModel = new InterfereBehaviorModel();
            $CrisisBehaviorModel = new CrisisBehaviorModel();
            $Behavior = $CrisisBehaviorModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['status','=',1]
            ])->select()->toArray();
            $data = [];
            foreach ($Behavior as $value){
                $data['name'][] = $value['name'];
                $interfere_id = $InterfereBehaviorModel->where('behavior_id','=',$value['id'])->distinct(true)->column('interfere_id');
                $data['num'][] = $InterfereUserModel->where([
                    ['id','in',$interfere_id],
                    ['time','between',[$start_time,$end_time]]
                ])->distinct(true)->count('uid');
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

}